package cn.com.assistant.controller;

import cn.com.assistant.annotation.AdminLoginToken;
import cn.com.assistant.utils.ResponseMessage;
import cn.com.assistant.utils.UUIDUtil;
import cn.com.assistant.utils.UploadImage;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Calendar;
import java.util.List;

@RestController
@RequestMapping("/image")
public class ImageController {

//    @AdminLoginToken
    @CrossOrigin(origins = "*",maxAge = 3600)
    @RequestMapping(value = "/upImage",method = RequestMethod.POST)
    @ApiOperation(value = "上传图片", notes = "上传图片")
    public ResponseMessage uploadBusinessImage(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
        if (null == file) {
            return ResponseMessage.failResponse().setMsg("没有上传文件！");
        }
        String result = uploadImage(file);
        return ResponseMessage.defaultResponse().setData(result).setMsg("上传成功！");
    }


    public static void main(String[] args) throws Exception{
        File file = new File("D:/test.jpg");

        FileInputStream fileInputStream = new FileInputStream(file);
        BufferedInputStream in = new BufferedInputStream(fileInputStream);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

        byte[] temp = new byte[1024];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] content = out.toByteArray();
        UploadImage.sshSftp(content, UUIDUtil.getUUID() +".jpg");
    }
    public String uploadImage(MultipartFile files) throws Exception {
        InputStream fileInputStream = files.getInputStream();
        BufferedInputStream in = new BufferedInputStream(fileInputStream);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);

        byte[] temp = new byte[1024];
        int size = 0;
        while ((size = in.read(temp)) != -1) {
            out.write(temp, 0, size);
        }
        in.close();
        byte[] content = out.toByteArray();
        String fileName = UUIDUtil.getUUID() +".jpg";
        UploadImage.sshSftp(content, fileName);
        return fileName;
    }

    /**
     *
     * @Title:图片上传返回路径
     * @Description
     * @param MultipartFile，request
     * @return  服务器保存的图片地址url
     * @throws
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public void upload(@RequestParam("file") MultipartFile files, HttpServletRequest request) {
        String dicName="UpFile";//服务器上传文件夹名称
        String newFileName=files.getOriginalFilename();
        newFileName=newFileName.substring(0,newFileName.lastIndexOf("."));
        String picurl = saveFile(files,newFileName,dicName, request);
    }

    public static String saveFile(MultipartFile filedata,String newFileName,String dicName, HttpServletRequest request) {
        // TODO Auto-generated method stub
        String pathval = request.getSession().getServletContext().getRealPath("/");
        // 根据配置文件获取服务器图片存放路径
        //String newFileName = String.valueOf(System.currentTimeMillis());
        Calendar cale = null;
        cale = Calendar.getInstance();
        String year = String.valueOf(cale.get(Calendar.YEAR));
        String month = String.valueOf(cale.get(Calendar.MONTH) + 1);
        String saveFilePath = "UpFile/"+dicName+"/"+year+"/"+month+"/";
        /* 构建文件目录 */
        File fileDir = new File(pathval + saveFilePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 上传的文件名
        String filename = filedata.getOriginalFilename();
        // 文件的扩张名
        String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
        try {
            String imgPath = saveFilePath + newFileName + "." + extensionName;
            // System.out.println(pathval + imgPath);打印图片位置
            FileOutputStream out = new FileOutputStream(pathval + imgPath);
            // 写入文件
            out.write(filedata.getBytes());
            out.flush();
            out.close();
            return imgPath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

